package se.topshelf.golftracker.web.controller.teetime;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import se.topshelf.golftracker.core.domain.TeeTime;
import se.topshelf.golftracker.core.service.BaseService;
import se.topshelf.golftracker.web.validator.BaseEntityValidator;

/**
 * Validates TeeBox entities, so that they are ok save.
 */
public class TeeTimeValidator extends BaseEntityValidator<TeeTime> {
    public static final String MAX_PARTICIPANTS_FIELD_NAME = "maxParticipants";
    public static final String COURSE_FIELD_NAME = "course";
    public static final String TEE_TIME_FIELD_NAME = "teeTime";
    private BaseService baseService;


    public TeeTimeValidator(BaseService baseService) {
        super(TeeTime.class);
        this.baseService = baseService;
    }


    @Override
    protected void validateFields(TeeTime entityToCheck, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, TEE_TIME_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, COURSE_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, MAX_PARTICIPANTS_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
    }

    @Override
    protected BaseService getBaseService() {
        return baseService;
    }

    @Override
    protected boolean isNaturalKeyEqual(TeeTime savedEntity, TeeTime entityToCheck) {
        //If any combination matches
        return savedEntity.getTeeTime().equals(entityToCheck.getTeeTime()) &&
                savedEntity.getCourse().equals(entityToCheck.getCourse()) &&
                savedEntity.getMaxParticipants().equals(entityToCheck.getMaxParticipants());
    }

    @Override
    protected void doRejectOfNaturalField(Errors errors, TeeTime entityToCheck) {
        errors.rejectValue(TEE_TIME_FIELD_NAME, "duplicate", "Duplicate field");
    }
}
